package com.hnepri.fang.ftx2.fetch.residential;

import com.hnepri.fang.ftx2.fetch.IPage;
import com.hnepri.util.StringUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import java.util.List;

public class ResidentialPageImpl implements IPage {
    /**
     * 解析小区dom列表为对象
     * @param elements
     * @return
     */
    private String getResidentialList(Elements elements) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < elements.size(); i++) {
            sb.append(getResidential(elements.get(i)) + System.getProperty("line.separator"));
        }
        return sb.toString();
    }
    /**
     * 把dom数据解析为java对象
     * @param element
     * @return
     */
    private String getResidential(Element element) {
        StringBuilder sb = new StringBuilder();
        try {
            Element urlEle = element.select("dd>p:eq(0)>a").get(0);
            String url = urlEle.attr("href");
            String projname = urlEle.text();
            String type = element.select("dd>p:eq(0)>span.plotFangType").text();
            String district = element.select("dd>p:eq(1)>a:eq(0)").text();
            String comarea = element.select("dd>p:eq(1)>a:eq(1)").text();
            List<Node> pDom2 = element.select("dd>p:eq(1)").get(0).childNodes();
            String address = pDom2.get(pDom2.size() - 1).toString();
            String price = element.select("div.listRiconwrap>p.priceAverage span:eq(0)").text();

            //除郑州市外，其它地市的小区简介都没有这些数据
            district = StringUtil.null2empty(district);
            comarea = StringUtil.null2empty(comarea);
            address = StringUtil.null2empty(address);

            sb.append(url + "|");
            sb.append(projname + "|");
            sb.append(type + "|");
            sb.append(district + "|");
            sb.append(comarea + "|");
            sb.append(address + "|");
            sb.append(price);
        } catch (Exception e) {
            System.out.println(element.html());
            e.printStackTrace();
            throw e;
        }
        return sb.toString();
    }
    @Override
    public String parse(String html) {
        Document doc = Jsoup.parseBodyFragment(html);
        Elements elements = doc.select("div.houseList>div.list");
        return getResidentialList(elements);
    }
}
